//
//  CHHomeViewController.swift
//  Checked
//
//  Created by Shinolr on 1/5/19.
//  Copyright © 2019 shinolr_go. All rights reserved.
//

import UIKit

let homeCellId = "homeCellIdentifier"

class CHHomeViewController: UIViewController {
    
    var dataArray = [CHMyShowsModel]()
    
    let tableView: UITableView = {
        let list = UITableView(frame: .zero, style: .plain)
        list.register(UINib.init(nibName: "CHHomeTableViewCell", bundle: nil), forCellReuseIdentifier: homeCellId)
        list.rowHeight = 80
        list.separatorStyle = .none
        list.backgroundColor = UIColor(hex: 0xF0F4F8)
        return list
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        
        guard AccessTokenModel.currentAccessToken != nil else {
            navigationController?.pushViewController(CHOAuthViewController(), animated: true)
            return
        }
        loadData()
        setupUI()
    }

    func loadData() {
//        traktProvider.request(.allShows) { (result) in
//            switch result {
//            case let .success(response):
//                let decoder = JSONDecoder()
//                do {
//                    print(String(bytes: response.data, encoding: .utf8)!)
//                    self.dataArray = try decoder.decode([CHMyShowsModel].self, from: response.data)
//                    self.tableView.reloadData()
//                } catch let error {
//                    print(error)
//                }
//            default: break
//            }
//        }
        
        traktProvider.request(.watched) { (result) in
            switch result {
            case let .success(response):
                print(String(bytes: response.data, encoding: .utf8)!)
            case .failure: break
            }
        }
    }

    func setupUI() {
        view.addSubview(tableView)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }

    func updateUI() {
        
    }
}

extension CHHomeViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: homeCellId, for: indexPath)
        guard let homeCell = cell as? CHHomeTableViewCell  else {
            fatalError("miss match CHHomeTableViewCell")
        }
        homeCell.selectionStyle = .none
        homeCell.model = dataArray[indexPath.row]
        
        return cell
    }
}
